//导入相关模块，本文以登陆功能为例,带参请求http://localhost:8088/user/login?name=yourval&password=yourval
import con from "./connect.js";
import userSQL from "./sql.js";
// 生成随机数，用于登录验证
import stringRandom from "string-random";

let sessionObj = new Map();

//登录
con.router.post("/api/login", (req, res) => {
  //本地接口路径http://localhost:8088/api/login
  let user = {
    userName: req.body.userName,
    userPass: req.body.userPass,
  };

  // 判断参数是否为空
  if (!user.userName) {
    return con.resJson(res, {
      code: 500,
      msg: "用户名不能为空",
    });
  }

  // 判断参数是否为空
  if (!user.userPass) {
    return con.resJson(res, {
      code: 500,
      msg: "密码不能为空",
    });
  }

  let _data;
  const sessran = stringRandom(16, { numbers: true });

  // 从连接池获取连接
  con.pool.getConnection((err, conn) => {
    //数据库链接
    conn.query(
      userSQL.userLogin,
      [user.userName, user.userPass],
      (e, result) => {
        //操作数据库
        if (e) {
          _data = {
            code: -1,
            msg: e,
          };
        }
        //通过用户名和密码索引查询数据，有数据说明用户存在且密码正确，只能返回登录成功，否则返回用户名不存在或登录密码错误
        if (result && result.length) {
          _data = {
            code: 200,
            msg: "登录成功",
            data: {
              userInfo: {
                id: result[0].id,
                session: sessran,
                userName: result[0].userName,
                userSex: result[0].userSex,
                userAge: result[0].userAge,
                userEmail: result[0].userEmail,
              },
            },
          };
          req.session.userinfo = sessran; // 设置session
          sessionObj.set(sessran, user.userName);
        } else {
          _data = {
            code: -1,
            msg: "用户名不存在或登录密码错误",
          };
        }
        setTimeout(() => {
          //把操作结果返回给前台页面
          con.resJson(res, _data);
        }, 500);
      }
    );
    con.pool.releaseConnection(conn); // 释放连接池，等待别的连接使用
  });
});

//注册信息
con.router.post("/api/register", (req, res) => {
  let user = {
    userName: req.body.userName,
    userPass: req.body.userPass,
    userAge: req.body.userAge,
    userEmail: req.body.userEmail,
    userSex: req.body.userSex,
    createTime: new Date().getTime(),
    updateTime: new Date().getTime(),
  };

  if (!user.userName) {
    return con.resJson(res, {
      code: 500,
      msg: "用户名不能为空",
    });
  }

  if (!user.userAge) {
    return con.resJson(res, {
      code: 500,
      msg: "年龄不能为空",
    });
  }
  // 从连接池获取连接
  con.pool.getConnection((err, conn) => {
    //数据库链接
    conn.query(
      userSQL.addUser,
      [
        user.userName,
        user.userPass,
        user.userAge,
        user.userSex,
        user.userEmail,
        user.createTime,
        user.updateTime,
      ],
      (e, result) => {
        let _data = {};
        //操作数据库
        if (e) {
          _data = {
            code: -1,
            msg: e,
          };
        }

        if (result) {
          _data = {
            code: 200,
            msg: "注册成功",
          };
        }

        setTimeout(() => {
          //把操作结果返回给前台页面
          con.resJson(res, _data);
        }, 500);
      }
    );
    con.pool.releaseConnection(conn); // 释放连接池，等待别的连接使用
  });
});

//获取用户列表
con.router.get("/api/userInfo", (req, res) => {
  let _data = {};
  if (session != req.headers.session) {
    return setTimeout(() => {
      _data = {
        code: 401,
        msg: "登录超时，请重新登录",
      };
      //把操作结果返回给前台页面
      con.resJson(res, _data);
    }, 500);
  }

  // 从连接池获取连接
  con.pool.getConnection((err, conn) => {
    //数据库链接
    conn.query(userSQL.selsctUser, (e, result) => {
      //操作数据库
      if (e) {
        _data = {
          code: -1,
          msg: e,
        };
      }

      if (result) {
        _data = {
          code: 200,
          data: result,
        };
      }

      setTimeout(() => {
        //把操作结果返回给前台页面
        con.resJson(res, _data);
      }, 500);
    });
    con.pool.releaseConnection(conn); // 释放连接池，等待别的连接使用
  });
});

//创建房间
con.router.post("/api/addRoom", (req, res) => {
  let room = {
    roomName: req.body.roomName,
    createTime: new Date().getTime(),
    updateTime: new Date().getTime(),
    created: req.body.created,
  };

  // 从连接池获取连接
  con.pool.getConnection((err, conn) => {
    //数据库链接
    let _data = {};
    conn.beginTransaction((err) => {
      new Promise((resolve, reject) => {
        conn.query(
          userSQL.addRoom,
          [room.roomName, room.createTime, room.updateTime, room.created],
          (e, result) => {
            //操作数据库
            if (e) {
              _data = {
                code: -1,
                msg: e,
              };
              reject(_data);
            }
            if (result) {
              resolve();
            }
          }
        );
      })
        .then(() => {
          return new Promise((resolve, reject) => {
            conn.query(
              `select * from room where created=${room.created}`,
              (e, result) => {
                if (e) {
                  _data = {
                    code: -1,
                    msg: e,
                  };
                  reject(_data);
                }

                if (result && result.length) {
                  resolve(result[result.length - 1]);
                }
              }
            );
          });
        })
        .then((data) => {
          return new Promise((_, reject) => {
            conn.query(
              userSQL.addUserRoom,
              [data.roomId, data.created],
              (e, result) => {
                if (e) {
                  _data = {
                    code: -1,
                    msg: e,
                  };
                  reject(_data);
                }
                if (result) {
                  _data = {
                    code: 200,
                    msg: "创建成功",
                  };
                  setTimeout(() => {
                    //把操作结果返回给前台页面
                    con.resJson(res, _data);
                  }, 500);
                }
                conn.commit();
              }
            );
          });
        })
        .catch((err) => {
          conn.rollback(() => {
            console.log("数据回滚");
          });
          setTimeout(() => {
            //把操作结果返回给前台页面
            con.resJson(res, err);
          }, 500);
        });
    });

    con.pool.releaseConnection(conn); // 释放连接池，等待别的连接使用
  });
});

//获取房间
con.router.get("/api/getRoom", (req, res) => {
  let query = {
    created: req.query.userId,
  };
  // 从连接池获取连接
  con.pool.getConnection((err, conn) => {
    //数据库链接
    conn.query(userSQL.selectRoom, [query.created], (e, result) => {
      let _data = {};
      //操作数据库
      if (e) {
        _data = {
          code: -1,
          msg: e,
        };
      } else {
        _data = {
          code: 200,
          data: result,
          msg: "查询成功",
        };
      }

      setTimeout(() => {
        //把操作结果返回给前台页面
        con.resJson(res, _data);
      }, 500);
    });
    con.pool.releaseConnection(conn); // 释放连接池，等待别的连接使用
  });
});

//退出或者解散房间
con.router.post("/api/delRoom", (req, res) => {
  let query = {
    userId: req.body.userId,
    roomId: req.body.roomId,
  };
  let _data = {};

  if (!query.userId) {
    return setTimeout(() => {
      _data = {
        code: 500,
        msg: "userId不能为空",
      };
      //把操作结果返回给前台页面
      con.resJson(res, _data);
    }, 500);
  }

  if (!query.roomId) {
    return setTimeout(() => {
      _data = {
        code: 500,
        msg: "roomId不能为空",
      };
      //把操作结果返回给前台页面
      con.resJson(res, _data);
    }, 500);
  }
  // 从连接池获取连接
  con.pool.getConnection((err, conn) => {
    conn.beginTransaction(() => {
      new Promise((resolve, reject) => {
        //先查询是否是创建者
        conn.query(
          userSQL.selectRoom2,
          [query.roomId, query.userId],
          (e, result) => {
            //操作数据库
            if (e) {
              _data = {
                code: -1,
                msg: e,
              };
              reject(_data);
            }
            //表示当前操作着是该房间的创建者
            if (result && result.length > 0) {
              resolve(1);
            } else {
              resolve(0);
            }
          }
        );
      })
        .then((bol) => {
          return new Promise((resave, reject) => {
            //解散群聊
            if (bol) {
              conn.query(
                userSQL.delRoom,
                [query.roomId, query.userId],
                (e, result) => {
                  if (e) {
                    _data = {
                      code: -1,
                      msg: e,
                    };
                    reject(_data);
                  }
                  if (result) {
                    resave();
                  }
                }
              );
            } else {
              //加入房间的人退出房间
              conn.query(
                userSQL.outUserInRoom,
                [query.roomId, query.userId],
                (e, result) => {
                  if (e) {
                    _data = {
                      code: -1,
                      msg: e,
                    };
                    reject(_data);
                  }
                  if (result) {
                    _data = {
                      code: 200,
                      msg: "退出成功",
                    };
                    setTimeout(() => {
                      //把操作结果返回给前台页面
                      con.resJson(res, _data);
                    }, 500);
                    conn.commit();
                  }
                }
              );
            }
          });
        })
        .then(() => {
          return new Promise((_, reject) => {
            //解除房间的所有关联者
            conn.query(userSQL.outUserInRoom2, [query.roomId], (e, result) => {
              if (e) {
                _data = {
                  code: -1,
                  msg: e,
                };
                reject(_data);
              }
              if (result) {
                _data = {
                  code: 200,
                  msg: "解散成功",
                };
                setTimeout(() => {
                  //把操作结果返回给前台页面
                  con.resJson(res, _data);
                }, 500);
                conn.commit();
              }
            });
          });
        })
        .catch((e) => {
          conn.rollback();
          setTimeout(() => {
            //把操作结果返回给前台页面
            con.resJson(res, e);
          }, 500);
        });
    });

    con.pool.releaseConnection(conn); // 释放连接池，等待别的连接使用
  });
});

//登出
con.router.post("/api/logout", (req, res) => {
  let _data = {};
  if (sessionObj.get()) {
    sessionObj.delete(req.body.session);
  }
  _data = {
    code: 200,
    msg: "登出成功！",
  };
  setTimeout(() => {
    //把操作结果返回给前台页面
    con.resJson(res, _data);
  }, 500);
});

//查询用户信息
con.router.get("/api/selUser", (req, res) => {
  let query = {
    id: req.query.id,
  };
  if (!query.id) {
    return setTimeout(() => {
      con.resJson(res, {
        code: 500,
        msg: "参数不能为空",
      });
    }, 500);
  }
  // 从连接池获取连接
  con.pool.getConnection((err, conn) => {
    //数据库链接
    conn.query(userSQL.selUserInfo, [query.id], (e, result) => {
      let _data = {};
      //操作数据库
      if (e) {
        _data = {
          code: -1,
          msg: e,
        };
      } else {
        _data = {
          code: 200,
          data: result[0],
          msg: "查询成功",
        };
      }

      setTimeout(() => {
        //把操作结果返回给前台页面
        con.resJson(res, _data);
      }, 500);
    });
    con.pool.releaseConnection(conn); // 释放连接池，等待别的连接使用
  });
});

//更新用户信息
con.router.post("/api/updateUser", (req, res) => {
  let query = {
    id: req.body.id,
    userName: req.body.userName,
    userAge: req.body.userAge,
    userSex: req.body.userSex,
    userEmail: req.body.userEmail,
    updateTime: new Date().getTime(),
  };
  // 从连接池获取连接
  con.pool.getConnection((err, conn) => {
    //数据库链接
    conn.query(
      userSQL.updateUser,
      [
        query.userName,
        query.userAge,
        query.userSex,
        query.userEmail,
        query.updateTime,
        query.id,
      ],
      (e, result) => {
        let _data = {};
        //操作数据库
        if (e) {
          _data = {
            code: -1,
            msg: e,
          };
        } else {
          _data = {
            code: 200,
            msg: "更新成功",
          };
        }

        setTimeout(() => {
          //把操作结果返回给前台页面
          con.resJson(res, _data);
        }, 500);
      }
    );
    con.pool.releaseConnection(conn); // 释放连接池，等待别的连接使用
  });
});

//用户修改密码
con.router.post("/api/updateUserPass", (req, res) => {
  let query = {
    id: req.body.id,
    userPass: req.body.newPass,
  };
  if (!query.userPass) {
    return setTimeout(() => {
      con.resJson(res, {
        code: 500,
        msg: "密码不能为空",
      });
    }, 500);
  }
  // 从连接池获取连接
  con.pool.getConnection((err, conn) => {
    //数据库链接
    conn.query(
      userSQL.updateUserPass,
      [query.userPass, query.id],
      (e, result) => {
        let _data = {};
        //操作数据库
        if (e) {
          _data = {
            code: -1,
            msg: e,
          };
        } else {
          _data = {
            code: 200,
            msg: "修改成功",
          };
        }

        setTimeout(() => {
          //把操作结果返回给前台页面
          con.resJson(res, _data);
        }, 500);
      }
    );
    con.pool.releaseConnection(conn); // 释放连接池，等待别的连接使用
  });
});

//获取群聊成员
con.router.post("/api/groupChats", (req, res) => {
  let query = {
    roomId: req.body.roomId,
  };
  let _data = {};
  if (!query.roomId) {
    return setTimeout(() => {
      _data = {
        code: 500,
        msg: "房间id不能为空",
      };
      con.resJson(res, _data);
    }, 500);
  }
  con.pool.getConnection((err, conn) => {
    conn.query(userSQL.groupChats, [query.roomId], (e, result) => {
      if (e) {
        setTimeout(() => {
          _data = {
            code: 500,
            msg: e,
          };
          con.resJson(res, _data);
        }, 500);
      }
      if (result && result.length) {
        setTimeout(() => {
          _data = {
            code: 200,
            data: result,
            msg: "查询成功",
          };
          con.resJson(res, _data);
        }, 500);
      }
    });
    con.pool.releaseConnection(conn); // 释放连接池，等待别的连接使用
  });
});

//加入群聊
con.router.post("/api/addInRoom", (req, res) => {
  let query = {
    userId: req.body.userId,
    roomName: req.body.roomName,
  };
  let _data = {};
  if (!query.userId) {
    return setTimeout(() => {
      _data = {
        code: 500,
        msg: "userId参数不能为空",
      };
      con.resJson(res, _data);
    }, 500);
  }

  if (!query.roomName) {
    return setTimeout(() => {
      _data = {
        code: 500,
        msg: "房间名称不能为空",
      };
      con.resJson(res, _data);
    }, 500);
  }
  con.pool.getConnection((err, conn) => {
    conn.query(userSQL.selectRoom3, [query.roomName], (e, result) => {
      if (e) {
        setTimeout(() => {
          _data = {
            code: 500,
            msg: e,
          };
          con.resJson(res, _data);
        }, 500);
      }
      if (result && result.length == 0) {
        setTimeout(() => {
          _data = {
            code: 500,
            msg: "房间不存在",
          };
          con.resJson(res, _data);
        }, 500);
      } else {
        setTimeout(() => {
          _data = {
            code: 200,
            data: result,
            msg: "查询成功",
          };
          con.resJson(res, _data);
        }, 500);
      }
    });

    con.pool.releaseConnection(conn); // 释放连接池，等待别的连接使用
  });
});

//搜索好友
con.router.get("/api/searchUser", (req, res) => {
  let query = {
    userName: req.query.userName,
  };
  let _data = {};

  if (!query.userName) {
    return setTimeout(() => {
      _data = {
        code: 500,
        msg: "userName参数不能为空",
      };
      con.resJson(res, _data);
    }, 500);
  }
  con.pool.getConnection((err, conn) => {
    conn.query(userSQL.selsctUser2, [query.userName], (e, result) => {
      if (e) {
        setTimeout(() => {
          _data = {
            code: 500,
            msg: e,
          };
          con.resJson(res, _data);
        }, 500);
      }
      if (result) {
        setTimeout(() => {
          _data = {
            code: 200,
            data: result,
            msg: "查询成功",
          };
          con.resJson(res, _data);
        }, 500);
      }
    });
    con.pool.releaseConnection(conn); // 释放连接池，等待别的连接使用
  });
});

export default con.router;
